package com.ihome.android.analytic;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.ihome.android.academy.db.UpdateAppInfo;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.market2.info.AppDetailInfo;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.info.BasicInfo;
import com.ihome.android.market2.info.CertificateInfo;
import com.ihome.android.market2.info.DownloadAppInfo;
import com.ihome.android.market2.info.HomepagecontentEdu;
import com.ihome.android.market2.info.LoginResult;
import com.ihome.android.market2.info.NavigationEdu;
import com.ihome.android.market2.info.PosterInfo;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.info.TopTitleEdu;
import com.ihome.android.market2.info.WelcomeInfo;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

/**
 * 各类Json数据解析
 * 
 * @author Emerson
 * 
 */
public class JsonAnalytic {
	public final String			TAG				= JsonAnalytic.class.getSimpleName();
	private static JsonAnalytic	jsonAnalytic	= null;

	public static JsonAnalytic getInstance() {
		if (null == jsonAnalytic) {
			jsonAnalytic = new JsonAnalytic();
		}
		return jsonAnalytic;
	}

	
	
	public List<TopTitleEdu> anslyseTopTitleEduResult(String json) throws ITVException {
		List<TopTitleEdu> topTitleEduList = null;
		try {
//			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(json);
			
		
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			if (0 != code)
				throw new ITVException("返回数据出错", code);
			JSONArray arr = jsonResult.optJSONArray("toptitlelist");
			Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

			topTitleEduList = g
			.fromJson(arr.toString(), new TypeToken<List<TopTitleEdu>>() {}.getType());

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return topTitleEduList;
	}
	
	
	public List<HomepagecontentEdu> homepagecontentEduEduResult(String json) throws ITVException {
		List<HomepagecontentEdu> homepagecontentEduList = null;
		try {
//			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(json);
			
		
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			if (0 != code)
				throw new ITVException("返回数据出错", code);
			JSONArray arr = jsonResult.optJSONArray("homepagecontentlist");
			Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

			homepagecontentEduList = g
			.fromJson(arr.toString(), new TypeToken<List<HomepagecontentEdu>>() {}.getType());

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return homepagecontentEduList;
	}
	
	
	/**
	 * 解析悦学堂返回的数据
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public NavigationEdu analyseNavigation(String json) throws ITVException {
		return analyseIndexJsonTemplate(json, NavigationEdu.class);
	}
	
	
	
	
	/**
	 * 模版解析
	 * 
	 * @param <T>
	 * @param json
	 * @param destClass
	 * @return
	 * @throws TVException
	 */
	public <T> T analyseJsonTemplate(String json, Class<T> destClass) throws ITVException {
		if (TextUtils.isEmpty(json)){
		}
		JSONObject jsonObj;

		try {
			JSONArray array = new JSONArray(json);
			jsonObj = new JSONObject(json);
			int code = jsonObj.optInt(HttpKeys.KEY_CODE);
			String msg = jsonObj.optString(HttpKeys.KEY_DESCRIPTION);
			if (ITVException.SUCCESS != code && ITVException.WELCOMECONFIG_NO_MATCH!=code && ITVException.FILE_SIZE_ERROR!=code && ITVException.FILE_UPLOAD_ERROR!=code &&ITVException.CODE_APP_CATEGORY_ONE!=code && ITVException.CODE_APP_CATEGORY_TWO!=code && ITVException.CODE_APP_CATEGORY_THREE!=code&& ITVException.CODE_CATEGORY_APP_ONE!=code && ITVException.CODE_CATEGORY_APP_TWO!=code){
				String[] msgx = {"","","","","",""};
				UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_NORMAL, "", msgx);
				throw new ITVException(msg, code);
			}
				
			return new Gson().fromJson(jsonObj.toString(), destClass);
		} catch (JSONException e) {
			String[] msgx = {"","","","","",""};
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_NORMAL, "", msgx);
			throw new ITVException(e);
		}
	}

	/**
	 * 模版解析
	 * 
	 * @param <T>
	 * @param json
	 * @param destClass
	 * @return
	 * @throws TVException
	 */
	public <T> T analyseIndexJsonTemplate(String json, Class<T> destClass) throws ITVException {
		JSONObject jsonObj;
		if (TextUtils.isEmpty(json)){
			throw new ITVException("解析数据为空",ITVException.JSON_ANALYTIC_STRING_NULL);
		}
			
		try {
			jsonObj = new JSONObject(json);
			int code = jsonObj.optInt(HttpKeys.KEY_CODE);
			if(code!=0){
				String msg = jsonObj.optString(HttpKeys.KEY_DESCRIPTION);
				throw new ITVException(msg, code);
			}
			
			return new Gson().fromJson(json, destClass);
		} catch (Exception e) {
			throw new ITVException(e);
		}
	}

	/**
	 * 解析简单的返回数据
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public BasicInfo analyseSimpleResult(String json) throws ITVException {
		return analyseJsonTemplate(json, BasicInfo.class);
	}

	/**
	 * 解析获取阴功签名证书（应用合法性校验）
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public CertificateInfo analyseCertificateResult(String json) throws ITVException {
		return analyseJsonTemplate(json, CertificateInfo.class);
	}

	/**
	 * 登陆接口解析
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public LoginResult anslyseLoginResult(String json) throws ITVException {
		JSONObject jsonObj = null;
		try {
			JSONArray array = new JSONArray(json);
			jsonObj = new JSONObject(array.getJSONObject(0).getString("results"));
			int code = jsonObj.optInt(HttpKeys.KEY_CODE);
			String msg = jsonObj.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code)
				throw new ITVException(msg, code);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return analyseIndexJsonTemplate(jsonObj.toString(), LoginResult.class);
	}

	/**
	 * 
	 * 
	 * [{"result":{"code":0, "description":"成功获取升级信息",
	 * "appURL":[{"appName":"应用商城", "pkgName":"com.ihome.android.market2",
	 * "fileName":"Com_ITV_Market_Client_1.0.1_20131024.apk", "url":
	 * "http://61.160.131.75:8081/vms/FileLocator?target=@ENC0@DKgX7HDaOQXWpv7oViIxRP+9BhLGwEOX1Ei3J1cOhpIqmGJgBK1As+mLm9RlqofwwrX3muBp1B1BLGUe8GAL6G4b/J188nskl6w6Lvah/eA="
	 * , "isUpdate":true, "version":"1.0.1"}]}}]
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public List<UpdateAppInfo> anslyseMarketUpdateAppResult(String json) throws ITVException {
		List<UpdateAppInfo> updateAppInfoList = null;
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("result"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code)
				throw new ITVException(msg, code);

			JSONArray kvArr = jsonResult.optJSONArray("appURL");
			Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

			updateAppInfoList = new Gson()
			.fromJson(kvArr.toString(), new TypeToken<List<UpdateAppInfo>>() {}.getType());

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return updateAppInfoList;
	}

	/**
	 * 获取应用详细
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public AppDetailInfo anslyseAppDetailResult(String json) throws ITVException {
		AppDetailInfo appDetail = null;
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code && 9003 != code)
				throw new ITVException(msg, code);

			appDetail = new Gson().fromJson(jsonResult.toString(), AppDetailInfo.class);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return appDetail;
	}


	/**
	 * 获取关联应用
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public List<AppInfo> anslyseAppInfoResult(String json) throws ITVException {
		List<AppInfo> appRelativeList = null;
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code && 9003 != code)
				throw new ITVException(msg, code);

			JSONArray arr = jsonResult.optJSONArray("item");
			Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

			//			java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<AppInfo>>(){}.getType();  
			appRelativeList = g.fromJson(arr.toString(), new TypeToken<List<AppInfo>>(){}.getType());	


			//			appRelativeList = new Gson().fromJson(arr.toString(), type);

		} catch (JSONException e) {
			LogUtil.i(TAG, "--> anslyseAppInfoResult()"+ e.getMessage());
			e.printStackTrace();
		}
		catch(JsonSyntaxException e){
			LogUtil.i(TAG, "--> anslyseAppInfoResult() if json is not a valid representation for an object of type typeOfT");
		}
		catch(JsonParseException e){
			LogUtil.i(TAG, "--> anslyseAppInfoResult() if json is not a valid representation for an object of type");

		}

		return appRelativeList;
	}


	/**
	 * [{"results":{"appUrl":
	 * "http://180.153.127.247:8080/andriod/FileLocator/?savename=8D8AA30978383BEBC145C6C81CC461A5.apk&target=@ENC0@oeHoDqhhZOPJqPD0LJOToLdLC6eQX/LHqYAWYD3HSuytQMoh/js7Hn9CHhA0qNAtb3gWXNf/6fq8N+OmNLFbKhInz6YPo7OL9LuuhMFnZo6tWxpTIqMnXfvcsRYEgruM"
	 * , "code":0, "description":"成功获取应用下载URL[21]"}}] 获取应用下载地址
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public String anslyseAppDLUrlResult(String json) throws ITVException {
		String appUrl = "";
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code)
				throw new ITVException(msg, code);

			appUrl = jsonResult.optString("appUrl");

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return appUrl;
	}


	/**
	 * 解析准备下载或需要升级App的MD5校验值
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public String anslyseAppDLMD5Result(String json) throws ITVException {
		String md5 = "";
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code)
				throw new ITVException(msg, code);

			md5 = jsonResult.optString("MD5");

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return md5;
	}


	/**
	 * 解析用户已下载的App和需要升级的App
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public List<DownloadAppInfo> anslyseAppResult(String json) throws ITVException {
		List<DownloadAppInfo> dlAppList = null;
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code && 9003 != code)
				throw new ITVException(msg, code);

			JSONArray arr = jsonResult.optJSONArray("item");
			dlAppList = new Gson().fromJson(arr.toString(), new TypeToken<List<DownloadAppInfo>>(){}.getType());

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return dlAppList;
	}

	/**
	 * 解析用户已下载的App和需要升级的App
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public List<AppInfo> anslyseUpdateAppResult(String json) throws ITVException {
		List<AppInfo> dlAppList = null;
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code && 9003 != code)
				throw new ITVException(msg, code);

			JSONArray arr = jsonResult.optJSONArray("item");
			Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

			dlAppList = g.fromJson(arr.toString(), new TypeToken<List<AppInfo>>() {}.getType());

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return dlAppList;
	}


	/**
	 * 推荐位海报接口解析
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public List<PosterInfo> anslysePosterInfo(String json) throws ITVException {

		ArrayList<PosterInfo> posterList = new ArrayList<PosterInfo>();
		try {

			JSONArray array = new JSONArray(json);
			JSONObject jsonObj = new JSONObject(array.getJSONObject(0).getString("results"));
			int code = jsonObj.optInt(HttpKeys.KEY_CODE);
			String msg = jsonObj.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code)
				throw new ITVException(msg, code);

			JSONArray arr = jsonObj.optJSONArray("item");
			posterList = new Gson().fromJson(arr.toString(), new TypeToken<List<PosterInfo>>() {}.getType());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return posterList;
	}

	/**
	 * 4.12 获取欢迎页
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public WelcomeInfo anslyseWelcomeInfo(String json) throws ITVException {
		return analyseJsonTemplate(json, WelcomeInfo.class);
	}

	/**
	 *  * 4.14 获取模板的栏目列表 <br>
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public List<TemplateContentInfo> anslyseTemplateContent(String json) throws ITVException {

		ArrayList<TemplateContentInfo> posterList = new ArrayList<TemplateContentInfo>();
		try {

			JSONArray array = new JSONArray(json);
			JSONObject jsonObj = new JSONObject(array.getJSONObject(0).getString("results"));
			int code = jsonObj.optInt(HttpKeys.KEY_CODE);
			String msg = jsonObj.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code)
				throw new ITVException(msg, code);

			JSONArray arr = jsonObj.optJSONArray("item");
			posterList = new Gson().fromJson(arr.toString(), new TypeToken<List<TemplateContentInfo>>() {}.getType());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return posterList;
	}

	/**
	 * 获取专题网页链接
	 * 
	 * @param json
	 * @return
	 * @throws ITVException
	 */
	public String anslyseSpecialTopicUrl(String json) throws ITVException {
		String specUrl = null;
		try {
			JSONArray array = new JSONArray(json);
			JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
			int code = jsonResult.optInt(HttpKeys.KEY_CODE);
			String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
			if (0 != code && 9003 != code)
				throw new ITVException(msg, code);

			specUrl = jsonResult.optString(HttpKeys.KEY_SPECIALURL);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return specUrl;
	}
}
